<?php
declare(strict_types=1);

ini_set('display_errors', '1');
ini_set('display_startup_errors', '1');
error_reporting(E_ALL);

ini_set('log_errors', '1');
ini_set('error_log', __DIR__ . '/php-error.log');

ob_start();
$cookieDomain = '.vsatdomains.com';
$secure = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off');

session_set_cookie_params([
    'lifetime' => 0,
    'path' => '/',
    'domain' => $cookieDomain,
    'secure' => $secure,
    'httponly' => true,
    'samesite' => 'Lax'
]);

session_start();

mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);

function normalizeHost(string $host): string {
    $host = strtolower(trim($host));
    $host = preg_replace('/:\d+$/', '', $host);
    return $host;
}

function redirect(string $url): void {
    if (!headers_sent()) {
        header('Location: ' . $url);
    }
    exit;
}

function is_valid_domain(string $name): bool {
    return (bool)preg_match(
        '/^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?(\.[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)*\.[a-z]{2,}$/i',
        $name
    );
}

function processCsvRow($data, $domainColIndex, $colMap, $dbPriceCols, $conn, &$messages, &$csvDomains) {
    $name = trim($data[$domainColIndex] ?? '');

    if (!is_valid_domain($name)) {
        $messages[] = "<p style='color:red;'>Invalid: " . htmlspecialchars($name) . "</p>";
        return;
    }

    $csvDomains[] = $name;

    $prices = [];
    foreach ($dbPriceCols as $col) {
        $idx = $colMap[$col] ?? null;
        $val = ($idx !== null) ? ($data[$idx] ?? '') : '';
        $prices[] = is_numeric($val) ? floatval($val) : 0.00;
    }

    $check = $conn->prepare("SELECT id FROM domains WHERE name = ?");
    $check->bind_param("s", $name);
    $check->execute();
    $check->store_result();

    if ($check->num_rows > 0) {

        if (array_sum($prices) == 0) {
            $del = $conn->prepare("DELETE FROM domains WHERE name = ?");
            $del->bind_param("s", $name);
            $del->execute();
            $del->close();

            $messages[] = "<p style='color:green;'>" . htmlspecialchars($name) . " deleted</p>";
        } else {
            $upd = $conn->prepare(
                "UPDATE domains
                 SET realtld_price=?, flatfeenames_price=?, domainfoxx_price=?, vsatdomains_price=?, domainsala_price=?, godaddy_price=?
                 WHERE name=?"
            );

            $params = array_merge($prices, [$name]);
            $upd->bind_param("dddddds", ...$params);
            $upd->execute();
            $upd->close();
        }

    } elseif (array_sum($prices) > 0) {

        $ins = $conn->prepare(
            "INSERT INTO domains
             (name,realtld_price,flatfeenames_price,domainfoxx_price,vsatdomains_price,domainsala_price,godaddy_price)
             VALUES (?,?,?,?,?,?,?)"
        );
        $ins->bind_param("sdddddd", $name, ...$prices);
        $ins->execute();
        $ins->close();

        $messages[] = "<p style='color:green;'>" . htmlspecialchars($name) . " added</p>";
    }

    $check->close();
}

try {
    $configPath = '/home/fvme60ccdm8r/config/config5.php';
    if (!is_readable($configPath)) {
        throw new Exception("Config file missing or not readable at: " . $configPath);
    }
    require_once $configPath;

    $conn = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);

    $is_admin = !empty($_SESSION['admin_logged_in']);

    // Redirect logic for mapped domains pointing to VSATDomains server
    $requested_domain = normalizeHost($_SERVER['HTTP_HOST'] ?? '');

    if ($requested_domain !== '' && $requested_domain !== 'vsatdomains.com' && $requested_domain !== 'www.vsatdomains.com') {

        $found = false;

        $stmt = $conn->prepare("SELECT 1 FROM dns_records WHERE domain_name = ? LIMIT 1");
        $stmt->bind_param("s", $requested_domain);
        $stmt->execute();
        $stmt->store_result();
        if ($stmt->num_rows > 0) { $found = true; }
        $stmt->close();

        if (!$found) {
            $stmt = $conn->prepare("SELECT 1 FROM domains WHERE name = ? LIMIT 1");
            $stmt->bind_param("s", $requested_domain);
            $stmt->execute();
            $stmt->store_result();
            if ($stmt->num_rows > 0) { $found = true; }
            $stmt->close();
        }

        if ($found) {
            $conn->close();
            ob_end_clean();
            redirect("/portfolio/landing.php?domain=" . urlencode($requested_domain));
        }
    }

    if (isset($_GET['logout'])) {
        session_destroy();
        redirect("/portfolio/index.php?page=1");
    }

    // DB columns must match your table exactly
    $dbPriceCols = [
        'realtld_price',
        'flatfeenames_price',
        'domainfoxx_price',
        'vsatdomains_price',
        'domainsala_price',
        'godaddy_price'
    ];

    // Where to send buyers for each seller button
    // VSATDomains is internal now, so it uses /portfolio/purchase.php
    $publicSellers = [
        'domainsala_price'   => ['label' => 'DomainSala',   'url' => 'http://domainsala.com/purchase.php'],
        'realtld_price'      => ['label' => 'RealTLD',      'url' => 'http://realtld.com/purchase.php'],
        'vsatdomains_price'  => ['label' => 'VSATDomains',  'url' => '/portfolio/purchase.php'],
        'domainfoxx_price'   => ['label' => 'DomainFoxx',   'url' => 'http://domainfoxx.com/purchase.php'],
        'flatfeenames_price' => ['label' => 'FlatFeeNames', 'url' => 'http://flatfeenames.com/purchase.php'],
        'godaddy_price'      => ['label' => 'GoDaddy',      'url' => 'https://www.godaddy.com/domains/searchresults.aspx?domainToCheck=']
    ];

    $domainHeaderAliases = ['domain name','domain','name','domain_name','domainname'];

    $priceHeaderAliases = [
        'realtld' => 'realtld_price',
        'realtld_price' => 'realtld_price',

        'flatfeenames' => 'flatfeenames_price',
        'flatfeenames_price' => 'flatfeenames_price',

        'domainfoxx' => 'domainfoxx_price',
        'domainfoxx_price' => 'domainfoxx_price',

        'vsatdomains' => 'vsatdomains_price',
        'vsatdomains_price' => 'vsatdomains_price',

        'domainsala' => 'domainsala_price',
        'domainsala_price' => 'domainsala_price',

        'godaddy' => 'godaddy_price',
        'godaddy_price' => 'godaddy_price'
    ];

    if ($_SERVER['REQUEST_METHOD'] === 'POST' && $is_admin) {

        if (isset($_POST['upload_domains_csv'], $_FILES['csv_file'])) {
            $messages = [];
            $csvDomains = [];

            if (($handle = fopen($_FILES['csv_file']['tmp_name'], "r")) !== false) {

                $firstRow = fgetcsv($handle, 5000, ",", '"', '\\');
                if ($firstRow === false) {
                    throw new Exception("CSV appears empty.");
                }

                $lowerFirstRow = array_map(function ($h) {
                    return strtolower(trim((string)$h));
                }, $firstRow);

                $hasHeader = false;
                foreach ($lowerFirstRow as $h) {
                    if (in_array($h, $domainHeaderAliases, true) || isset($priceHeaderAliases[$h])) {
                        $hasHeader = true;
                        break;
                    }
                }

                $colMap = [];
                $domainColIndex = 0;

                if ($hasHeader) {
                    foreach ($lowerFirstRow as $i => $h) {
                        if (in_array($h, $domainHeaderAliases, true)) {
                            $domainColIndex = $i;
                            continue;
                        }
                        if (isset($priceHeaderAliases[$h])) {
                            $colMap[$priceHeaderAliases[$h]] = $i;
                        }
                    }
                } else {
                    // No-header CSV fixed order:
                    // 0 domain, 1 realtld, 2 flatfeenames, 3 domainfoxx, 4 vsatdomains, 5 domainsala, 6 godaddy
                    $domainColIndex = 0;
                    $fixed = [
                        1 => 'realtld_price',
                        2 => 'flatfeenames_price',
                        3 => 'domainfoxx_price',
                        4 => 'vsatdomains_price',
                        5 => 'domainsala_price',
                        6 => 'godaddy_price'
                    ];
                    foreach ($fixed as $i => $col) {
                        $colMap[$col] = $i;
                    }
                }

                if (!$hasHeader) {
                    $data = $firstRow;
                    processCsvRow($data, $domainColIndex, $colMap, $dbPriceCols, $conn, $messages, $csvDomains);
                }

                while (($data = fgetcsv($handle, 5000, ",", '"', '\\')) !== false) {
                    processCsvRow($data, $domainColIndex, $colMap, $dbPriceCols, $conn, $messages, $csvDomains);
                }

                fclose($handle);
            }

            $csvDomains = array_values(array_unique($csvDomains));
            if (count($csvDomains) > 0) {
                $placeholders = implode(',', array_fill(0, count($csvDomains), '?'));
                $types = str_repeat('s', count($csvDomains));

                $delSql = "DELETE FROM domains WHERE name NOT IN ($placeholders)";
                $delStmt = $conn->prepare($delSql);
                $delStmt->bind_param($types, ...$csvDomains);
                $delStmt->execute();
                $deletedCount = $delStmt->affected_rows;
                $delStmt->close();

                $messages[] = "<p style='color:green;'>Sync cleanup: {$deletedCount} domains removed because they were not in the CSV.</p>";
            } else {
                $messages[] = "<p style='color:red;'>No valid domains found in CSV. Sync cleanup skipped.</p>";
            }

            $_SESSION['csv_messages'] = $messages;
            redirect("/portfolio/index.php?page=1");
        }

        if (isset($_POST['edit'])) {
            $name = trim($_POST['name'] ?? '');
            $id = (int)($_POST['id'] ?? 0);

            $prices = array_map('floatval', [
                $_POST['realtld_price'] ?? 0,
                $_POST['flatfeenames_price'] ?? 0,
                $_POST['domainfoxx_price'] ?? 0,
                $_POST['vsatdomains_price'] ?? 0,
                $_POST['domainsala_price'] ?? 0,
                $_POST['godaddy_price'] ?? 0
            ]);

            $stmt = $conn->prepare(
                "UPDATE domains
                 SET name=?, realtld_price=?, flatfeenames_price=?, domainfoxx_price=?, vsatdomains_price=?, domainsala_price=?, godaddy_price=?
                 WHERE id=?"
            );

            $params = array_merge([$name], $prices, [$id]);
            $stmt->bind_param("sddddddi", ...$params);
            $stmt->execute();
            $stmt->close();

            redirect("/portfolio/index.php?page=1");
        }

        if (isset($_POST['add'])) {
            $name = trim($_POST['name'] ?? '');

            $prices = array_map('floatval', [
                $_POST['realtld_price'] ?? 0,
                $_POST['flatfeenames_price'] ?? 0,
                $_POST['domainfoxx_price'] ?? 0,
                $_POST['vsatdomains_price'] ?? 0,
                $_POST['domainsala_price'] ?? 0,
                $_POST['godaddy_price'] ?? 0
            ]);

            $check = $conn->prepare("SELECT id FROM domains WHERE name = ?");
            $check->bind_param("s", $name);
            $check->execute();
            $check->store_result();

            if ($check->num_rows == 0 && $name !== '') {
                $ins = $conn->prepare(
                    "INSERT INTO domains
                     (name,realtld_price,flatfeenames_price,domainfoxx_price,vsatdomains_price,domainsala_price,godaddy_price)
                     VALUES (?,?,?,?,?,?,?)"
                );
                $ins->bind_param("sdddddd", $name, ...$prices);
                $ins->execute();
                $ins->close();
            }

            $check->close();
            redirect("/portfolio/index.php?page=1");
        }
    }

    if (isset($_GET['delete'], $_GET['id']) && $is_admin) {
        $stmt = $conn->prepare("DELETE FROM domains WHERE id = ?");
        $id = (int)$_GET['id'];
        $stmt->bind_param("i", $id);
        $stmt->execute();
        $stmt->close();

        redirect("/portfolio/index.php?page=1");
    }

    if (isset($_GET['download_domains_csv']) && $is_admin) {
        header('Content-Type: text/csv');
        header('Content-Disposition: attachment; filename="domains.csv"');

        $output = fopen('php://output', 'w');
        fputcsv($output, [
            'Domain Name',
            'RealTLD',
            'FlatFeeNames',
            'DomainFoxx',
            'VSATDomains',
            'DomainSala',
            'GoDaddy'
        ]);

        $res = $conn->query(
            "SELECT name,realtld_price,flatfeenames_price,domainfoxx_price,vsatdomains_price,domainsala_price,godaddy_price
             FROM domains
             ORDER BY name"
        );

        while ($row = $res->fetch_assoc()) {
            fputcsv($output, $row);
        }

        $res->free();
        $conn->close();
        exit;
    }

    $messages = $_SESSION['csv_messages'] ?? [];
    unset($_SESSION['csv_messages']);

    $search = trim($_GET['search'] ?? '');
    $page = max(1, (int)($_GET['page'] ?? 1));
    $perPage = 24;
    $offset = ($page - 1) * $perPage;

    $whereSql = "";
    $params = [];
    $types = "";

    if ($search !== "") {
        $whereSql = "WHERE name LIKE ?";
        $params[] = "%" . $search . "%";
        $types .= "s";
    }

    if ($whereSql) {
        $countStmt = $conn->prepare("SELECT COUNT(*) AS total FROM domains $whereSql");
        $countStmt->bind_param($types, ...$params);
        $countStmt->execute();
        $total = (int)$countStmt->get_result()->fetch_assoc()['total'];
        $countStmt->close();
    } else {
        $total = (int)$conn->query("SELECT COUNT(*) AS total FROM domains")->fetch_assoc()['total'];
    }

    $totalPages = max(1, (int)ceil($total / $perPage));

    if ($whereSql) {
        $sql = "SELECT * FROM domains $whereSql ORDER BY name LIMIT ? OFFSET ?";
        $stmt = $conn->prepare($sql);
        $pageParams = array_merge($params, [$perPage, $offset]);
        $stmt->bind_param($types . "ii", ...$pageParams);
    } else {
        $sql = "SELECT * FROM domains ORDER BY name LIMIT ? OFFSET ?";
        $stmt = $conn->prepare($sql);
        $stmt->bind_param("ii", $perPage, $offset);
    }

    $stmt->execute();
    $domains = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
    $stmt->close();

} catch (Throwable $e) {
    http_response_code(500);
    echo "<pre style='white-space:pre-wrap;color:red;'>";
    echo "FATAL ERROR: " . htmlspecialchars($e->getMessage()) . "\n";
    echo "File: " . htmlspecialchars($e->getFile()) . "\n";
    echo "Line: " . (int)$e->getLine() . "\n";
    echo "</pre>";
    ob_end_flush();
    exit;
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>VSATDomains - Premium Domain Marketplace</title>
    <meta name="description" content="VSATDomains is your marketplace for premium domain names. Search curated domains, compare prices across trusted sellers, and purchase securely.">
    <meta name="robots" content="<?php echo $is_admin ? 'noindex, nofollow' : 'index, follow'; ?>">
    <link rel="stylesheet" href="/portfolio/styles.css">
    <style>
        .delete-link{color:#ff4444;text-decoration:none;margin-left:1rem}
        .edit-link{color:#0066cc;text-decoration:none;margin-left:1rem}
        .edit-form{display:none;margin-top:1rem;background:#fff;padding:1rem;border:1px solid #ddd;border-radius:5px}
        .edit-form.active{display:block}
        nav a{color:white;margin:0 15px;text-decoration:none}
        .domain-grid{display:grid;grid-template-columns:repeat(auto-fill,minmax(300px,1fr));gap:20px;margin-top:20px}
        .domain{background:#fff;padding:15px;border:1px solid #eee;border-radius:8px}
        .price-list li{margin:8px 0;display:flex;justify-content:space-between;align-items:center}
        .admin-box{background:#f7f7f7;padding:15px;border:1px solid #ddd;border-radius:8px;margin-bottom:20px}
        .admin-box input{width:100%;padding:6px;margin:4px 0}
        .btn{display:inline-block;padding:8px 12px;background:#1a73e8;color:white;border-radius:4px;text-decoration:none;border:none;cursor:pointer}
        .btn:hover{background:#1557b0}
        .pagination a{margin:0 5px;text-decoration:none}
        .pagination .current{font-weight:bold}
        form.inline{display:inline}
        .primary-buy{display:block;width:100%;text-align:center;padding:10px 12px;background:#000;color:#fff;border-radius:6px;text-decoration:none;font-weight:700;margin:10px 0 12px}
        .primary-buy:hover{opacity:0.92}
        .badge{display:inline-block;font-size:11px;font-weight:700;padding:2px 6px;border-radius:10px;background:#e8f0fe;color:#1a73e8;margin-left:6px;vertical-align:middle}
        .price-list li.recommended{background:#f7f7f7;border-radius:6px;padding:6px 8px}
        .price-list li.godaddy-row{opacity:0.9;font-size:0.98em}
        .edit-grid{display:grid;grid-template-columns:140px 1fr;gap:8px 10px;align-items:center;margin-top:8px}
        .edit-grid label{font-size:14px;font-weight:600;color:#222;text-align:right;padding-right:6px}
        .edit-grid input{width:100%;padding:6px}
        @media (max-width:600px){
            .edit-grid{grid-template-columns:1fr}
            .edit-grid label{text-align:left;padding-right:0;margin-top:6px}
        }
    </style>
    <script>
        function toggleEdit(id){
            var el = document.getElementById('edit-' + id);
            if(el){ el.classList.toggle('active'); }
        }
    </script>
</head>
<body>

<header style="background:#000;color:white;padding:20px;text-align:center">
    <h1>VSAT Domains</h1>
    <p>Your destination for premium domain names</p>
    <nav>
        <a href="/portfolio/index.php?page=1">Home</a>
        <a href="/portfolio/about.php">About</a>
        <a href="/portfolio/contact.php">Contact</a>
        <a href="/portfolio/terms.php">Terms</a>
        <a href="/portfolio/privacy.php">Privacy</a>
        <?php if ($is_admin): ?>
            <a href="/portfolio/index.php?logout=1" style="color:#ff9999">Logout</a>
        <?php else: ?>
            <a href="/portfolio/login.php">Admin Login</a>
        <?php endif; ?>
    </nav>
</header>

<div style="max-width:1200px;margin:20px auto;padding:20px;background:white;border-radius:8px">

    <?php foreach ($messages as $m) { echo $m; } ?>

    <form method="get" action="/portfolio/index.php" style="margin-bottom:15px;display:flex;gap:8px;">
        <input type="text" name="search" placeholder="Search domains..." value="<?php echo htmlspecialchars($search); ?>" style="flex:1;padding:8px">
        <button class="btn" type="submit">Search</button>
        <input type="hidden" name="page" value="1">
    </form>

    <div style="display:flex;justify-content:flex-end;margin-bottom:10px;">
        <a href="/portfolio/all-domains.php" class="btn" style="background:#000;">
            View All Domains
        </a>
    </div>

    <?php if ($is_admin): ?>
        <div class="admin-box">
            <h3>Admin Panel</h3>

            <div style="margin-bottom:10px;">
                <form class="inline" method="post" enctype="multipart/form-data">
                    <input type="file" name="csv_file" required>
                    <button class="btn" type="submit" name="upload_domains_csv" value="1">Upload CSV</button>
                </form>

                <a class="btn" href="/portfolio/index.php?download_domains_csv=1">Download CSV</a>
            </div>

            <form method="post">
                <h4>Add Domain</h4>
                <input type="text" name="name" placeholder="domain.com" required>

                <div class="edit-grid">
                    <label for="add-realtld">RealTLD</label>
                    <input id="add-realtld" name="realtld_price" placeholder="RealTLD">

                    <label for="add-flatfee">FlatFeeNames</label>
                    <input id="add-flatfee" name="flatfeenames_price" placeholder="FlatFeeNames">

                    <label for="add-domainfoxx">DomainFoxx</label>
                    <input id="add-domainfoxx" name="domainfoxx_price" placeholder="DomainFoxx">

                    <label for="add-vsat">VSATDomains</label>
                    <input id="add-vsat" name="vsatdomains_price" placeholder="VSATDomains">

                    <label for="add-domainsala">DomainSala</label>
                    <input id="add-domainsala" name="domainsala_price" placeholder="DomainSala">

                    <label for="add-godaddy">GoDaddy</label>
                    <input id="add-godaddy" name="godaddy_price" placeholder="GoDaddy">
                </div>

                <button class="btn" type="submit" name="add" value="1" style="margin-top:8px;">Add Domain</button>
            </form>
        </div>
    <?php endif; ?>

    <div class="domain-grid">
        <?php if (empty($domains)): ?>
            <p>No domains found.</p>
        <?php endif; ?>

        <?php foreach ($domains as $d): ?>
            <div class="domain">
                <h3><?php echo htmlspecialchars($d['name']); ?></h3>

                <?php
                    $bestCol = null;
                    $bestLabel = null;
                    $bestPrice = null;

                    foreach ($publicSellers as $colKey => $metaKey) {
                        if ($metaKey['label'] === 'GoDaddy') { continue; }
                        $p = floatval($d[$colKey] ?? 0);
                        if ($p > 0 && ($bestPrice === null || $p < $bestPrice)) {
                            $bestPrice = $p;
                            $bestCol = $colKey;
                            $bestLabel = $metaKey['label'];
                        }
                    }

                    $preferredBuyLink = null;
                    if ($bestCol && !empty($publicSellers[$bestCol]['url'])) {
                        $base = $publicSellers[$bestCol]['url'];

                        if (strpos($base, '/portfolio/purchase.php') === 0) {
                            $preferredBuyLink =
                                $base
                                . "?domain=" . urlencode($d['name'])
                                . "&price=" . urlencode((string)$bestPrice)
                                . "&brand=" . urlencode((string)$bestLabel);
                        } else {
                            $preferredBuyLink =
                                $base
                                . "?domain=" . urlencode($d['name'])
                                . "&price=" . urlencode((string)$bestPrice)
                                . "&brand=" . urlencode((string)$bestLabel);
                        }
                    }
                ?>

                <?php if ($preferredBuyLink): ?>
                    <a class="primary-buy" href="<?php echo $preferredBuyLink; ?>" target="_blank" rel="noopener noreferrer">
                        Buy securely through our Best Price Partner
                    </a>
                <?php endif; ?>

                <ul class="price-list">
                    <?php foreach ($publicSellers as $col => $meta): ?>
                        <?php
                            $label = $meta['label'];
                            $url = $meta['url'];
                            $price = floatval($d[$col] ?? 0);

                            if ($label !== 'GoDaddy' && $price <= 0) { continue; }

                            $isRecommended = ($bestCol === $col && $price > 0);
                        ?>
                        <li class="<?php echo $isRecommended ? 'recommended' : ''; ?> <?php echo ($label === 'GoDaddy') ? 'godaddy-row' : ''; ?>">
                            <span>
                                <?php
                                    if ($label === 'GoDaddy') {
                                        echo ($price > 0)
                                            ? "GoDaddy marketplace: $" . number_format($price, 0)
                                            : "GoDaddy marketplace:";
                                    } else {
                                        echo $label . ": $" . number_format($price, 0);
                                        if ($isRecommended) {
                                            echo " <span class='badge'>Recommended</span>";
                                        }
                                    }
                                ?>
                            </span>

                            <?php if ($label === 'GoDaddy'): ?>
                                <a href="<?php echo $url . urlencode($d['name']); ?>" target="_blank" rel="noopener noreferrer">
                                    <?php echo ($price > 0) ? "Purchase at GoDaddy" : "Check price"; ?>
                                </a>
                            <?php elseif ($url): ?>
                                <?php
                                    $sellerPrice = floatval($d[$col] ?? 0);
                                    $buyLink = $url
                                        . "?domain=" . urlencode($d['name'])
                                        . "&price=" . urlencode((string)$sellerPrice)
                                        . "&brand=" . urlencode((string)$label);
                                ?>
                                <a href="<?php echo $buyLink; ?>" target="_blank" rel="noopener noreferrer">Buy on <?php echo htmlspecialchars($label); ?></a>
                            <?php endif; ?>
                        </li>
                    <?php endforeach; ?>
                </ul>

                <a href="/portfolio/landing.php?domain=<?php echo urlencode($d['name']); ?>" class="btn">More Info</a>

                <?php if ($is_admin): ?>
                    <a href="javascript:void(0)" class="edit-link" onclick="toggleEdit(<?php echo (int)$d['id']; ?>)">Edit</a>
                    <a href="/portfolio/index.php?delete=1&id=<?php echo (int)$d['id']; ?>" class="delete-link" onclick="return confirm('Delete this domain?')">Delete</a>

                    <form method="post" id="edit-<?php echo (int)$d['id']; ?>" class="edit-form">
                        <input type="hidden" name="id" value="<?php echo (int)$d['id']; ?>">
                        <input type="text" name="name" value="<?php echo htmlspecialchars($d['name']); ?>" required>

                        <div class="edit-grid">
                            <label for="edit-realtld-<?php echo (int)$d['id']; ?>">RealTLD</label>
                            <input id="edit-realtld-<?php echo (int)$d['id']; ?>" name="realtld_price" value="<?php echo htmlspecialchars((string)$d['realtld_price']); ?>">

                            <label for="edit-flatfee-<?php echo (int)$d['id']; ?>">FlatFeeNames</label>
                            <input id="edit-flatfee-<?php echo (int)$d['id']; ?>" name="flatfeenames_price" value="<?php echo htmlspecialchars((string)$d['flatfeenames_price']); ?>">

                            <label for="edit-domainfoxx-<?php echo (int)$d['id']; ?>">DomainFoxx</label>
                            <input id="edit-domainfoxx-<?php echo (int)$d['id']; ?>" name="domainfoxx_price" value="<?php echo htmlspecialchars((string)$d['domainfoxx_price']); ?>">

                            <label for="edit-vsat-<?php echo (int)$d['id']; ?>">VSATDomains</label>
                            <input id="edit-vsat-<?php echo (int)$d['id']; ?>" name="vsatdomains_price" value="<?php echo htmlspecialchars((string)$d['vsatdomains_price']); ?>">

                            <label for="edit-domainsala-<?php echo (int)$d['id']; ?>">DomainSala</label>
                            <input id="edit-domainsala-<?php echo (int)$d['id']; ?>" name="domainsala_price" value="<?php echo htmlspecialchars((string)$d['domainsala_price']); ?>">

                            <label for="edit-godaddy-<?php echo (int)$d['id']; ?>">GoDaddy</label>
                            <input id="edit-godaddy-<?php echo (int)$d['id']; ?>" name="godaddy_price" value="<?php echo htmlspecialchars((string)$d['godaddy_price']); ?>">
                        </div>

                        <button class="btn" type="submit" name="edit" value="1" style="margin-top:8px;">Save</button>
                    </form>
                <?php endif; ?>
            </div>
        <?php endforeach; ?>
    </div>

    <div class="pagination" style="text-align:center;margin-top:20px;">
        <?php if ($totalPages > 1): ?>
            <?php for ($i=1; $i<=$totalPages; $i++): ?>
                <?php if ($i == $page): ?>
                    <span class="current"><?php echo $i; ?></span>
                <?php else: ?>
                    <a href="/portfolio/index.php?page=<?php echo $i; ?>&search=<?php echo urlencode($search); ?>"><?php echo $i; ?></a>
                <?php endif; ?>
            <?php endfor; ?>
        <?php endif; ?>
    </div>

</div>

<?php ob_end_flush(); ?>
</body>
</html>
<?php $conn->close(); ?>
